<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="营地" prop="userId">
        <el-select v-model="queryParams.campId" placeholder="请选择营地" clearable>
          <el-option
            v-for="camp in campList"
            :key="camp.campId"
            :label="camp.campName"
            :value="camp.campId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户 " prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户 " clearable>
          <el-option
            v-for="campUser in userList"
            :key="campUser.userId"
            :label="campUser.username"
            :value="campUser.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约时间" prop="appointTime">
        <el-date-picker clearable
                        v-model="queryParams.appointTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择预约状态" clearable>
          <el-option
            v-for="dict in dict.type.c_appoint_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['camp:appointment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['camp:appointment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['camp:appointment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['camp:appointment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="预约Id" align="center" prop="appointId" />-->
<!--      <el-table-column label="营地Id" align="center" prop="campId" />
      <el-table-column label="用户Id" align="center" prop="userId" />-->
      <el-table-column label="营地" align="center" prop="campName" />
      <el-table-column label="用户" align="center" prop="username" />
      <el-table-column label="总金额" align="center" prop="amount" />
      <el-table-column label="预约时间" align="center" prop="appointTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.appointTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.c_appoint_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="预约二维码" align="center" prop="qrcode" />
      <el-table-column label="操作" align="center" class-name="small-padding " width="280">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['camp:appointment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['camp:appointment:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAddDetail(scope.row)"
            v-hasPermi="['camp:appointment:addDetail']"
          >新增详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleShowDetail(scope.row)"
            v-hasPermi="['camp:appointment:showDetails']"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="营地" prop="userId">
          <el-select v-model="form.campId" placeholder="请选择营地" clearable>
            <el-option
              v-for="camp in campList"
              :key="camp.campId"
              :label="camp.campName"
              :value="camp.campId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户 " prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户 " clearable>
            <el-option
              v-for="campUser in userList"
              :key="campUser.userId"
              :label="campUser.username"
              :value="campUser.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="总金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointTime">
          <el-date-picker clearable
                          v-model="form.appointTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择预约状态">
            <el-option
              v-for="dict in dict.type.c_appoint_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约二维码" prop="qrcode">
          <el-input v-model="form.qrcode" placeholder="请输入预约二维码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增详情弹框 -->
    <el-dialog title="新增预约详情" :visible.sync="openDetail" width="500px" append-to-body>
      <el-form ref="formDetail" :model="formDetail" :rules="rulesDetail" label-width="80px">
        <el-form-item label="预约Id" prop="appointId">
          <el-input v-model="formDetail.appointId" placeholder="请输入预约Id" />
        </el-form-item>
        <el-form-item label="产品类型" prop="type">
          <el-select v-model="formDetail.type" placeholder="请选择产品类型" v-on:change="changeDetailType">
            <el-option
              v-for="dict in dict.type.c_detail_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营位Id" prop="campsiteId" v-if="showCampsite">
          <el-select v-model="formDetail.campsiteId" placeholder="请选择营位" v-on:change="changeCampsite">
            <el-option
              v-for="dict in campsiteList"
              :key="dict.campsiteId"
              :label="dict.campsiteName"
              :value="dict.campsiteId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目Id" prop="projectId" v-if="showProject">
          <el-select v-model="formDetail.projectId" placeholder="请选择项目" v-on:change="changeProject">
            <el-option
              v-for="dict in projectList"
              :key="dict.projectId"
              :label="dict.projectName"
              :value="dict.projectId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动Id" prop="activityId" v-if="showActivity">
          <el-select v-model="formDetail.activityId" placeholder="请选择活动" v-on:change="changeActivity">
            <el-option
              v-for="dict in activityList"
              :key="dict.activityId"
              :label="dict.activityName"
              :value="dict.activityId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="number">
          <el-input v-model="formDetail.number" placeholder="请输入数量"
                    v-on:input="formDetail.unitPrice=formDetail.number*price"/>
        </el-form-item>
        <el-form-item label="单价" prop="number">
          <el-input v-model="price" placeholder="原价" readonly />
        </el-form-item>
        <el-form-item label="金额" prop="unitPrice">
          <el-input v-model="formDetail.unitPrice" placeholder="金额" readonly/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormDetail">确 定</el-button>
        <el-button @click="cancelDetail">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看详情弹框 -->
    <el-dialog title="查看预约详情" :visible.sync="openDetailList" width="600px" append-to-body>
      <el-table v-loading="loading" :data="detailsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="预约详情Id" align="center" prop="detailId" />
        <el-table-column label="预约Id" align="center" prop="appointId" />-->
        <el-table-column label="产品类型" align="center" prop="type">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.c_detail_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
<!--        <el-table-column label="营位Id" align="center" prop="campsiteId" />
        <el-table-column label="项目Id" align="center" prop="projectId" />
        <el-table-column label="活动Id" align="center" prop="activityId" />-->
        <el-table-column label="数量" align="center" prop="number" />
        <el-table-column label="金额" align="center" prop="unitPrice" />
<!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['camp:details:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['camp:details:remove']"
            >删除</el-button>
          </template>
        </el-table-column>-->
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listAppointment, getAppointment, delAppointment, addAppointment, updateAppointment } from "@/api/camp/appointment";
import {allCampUser} from "@/api/camp/campUser";
import {allCamp } from "@/api/camp/camp";
import { listDetails,  addDetails } from "@/api/camp/details";
import {listProject} from "@/api/camp/project";
import {listActivity} from "@/api/camp/activity";
import {listCampsite} from "@/api/camp/campsite";

export default {
  name: "Appointment",
  dicts: ['c_appoint_state','c_detail_type'],
  data() {
    return {
      //单价
      price:0,
      showProject:false,
      showActivity:false,
      showCampsite:false,
      //项目列表
      projectList:[],
      //活动列表
      activityList:[],
      //营位列表
      campsiteList:[],
      //预约详情列表
      detailsList:[],
      //详情显示
      openDetailList:false,
      //新增详情
      openDetail:false,
      // 表单参数
      formDetail: {},
      // 表单校验
      rulesDetail: {
        number: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "金额不能为空", trigger: "blur" }
        ]
      },


      //微信用户列表
      userList:[],
      //营地列表
      campList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约管理表格数据
      appointmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        campId: null,
        userId: null,
        amount: null,
        appointTime: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        amount: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
        appointTime: [
          { required: true, message: "预约时间不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "预约状态不能为空", trigger: "change" }
        ],
        qrcode: [
          { required: true, message: "预约二维码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    //请求后台，获取微信用户数据
    allCampUser().then(response => {
      this.userList = response.rows;
    });
    //请求后台，获取营地数据
    allCamp().then(response => {
      this.campList = response.rows;
    });
  },
  methods: {
    //营位下拉框发生变化
    changeCampsite(){
      //alert(this.formDetail.campsiteId)
      for (let i=0;i<this.campsiteList.length;i++){
        if (this.campsiteList[i].campsiteId==this.formDetail.campsiteId){
          this.price = this.campsiteList[i].originalPrice
          break;
        }
      }
    },
    changeProject(){
      //alert(this.formDetail.projectId)
      for (let i=0;i<this.projectList.length;i++){
        if (this.projectList[i].projectId==this.formDetail.projectId){
          this.price = this.projectList[i].originalPrice
          break;
        }
      }
    },
    changeActivity(){
      //alert(this.formDetail.activityId)
      for (let i=0;i<this.activityList.length;i++){
        if (this.activityList[i].activityId==this.formDetail.activityId){
          this.price = this.activityList[i].originalPrice
          break;
        }
      }
    },
    //产品类型发生变化的时候：
    changeDetailType(){
      //alert(this.formDetail.type)
      if (this.formDetail.type==1){
        listCampsite({"campId":this.formDetail.campId}).then(response => {
          this.campsiteList = response.rows;
          this.showCampsite=true
        });
      }else  if (this.formDetail.type==2){
        listProject({"campId":this.formDetail.campId}).then(response => {
          this.projectList = response.rows;
          this.showProject=true
        });
      }else  if (this.formDetail.type==3){
        listActivity({"campId":this.formDetail.campId}).then(response => {
          this.activityList = response.rows;
          this.showActivity=true
        });
      }
    },
    //查询详情列表
    handleShowDetail(row){
      this.openDetailList = true
      this.getDetailsList(row.appointId)
    },
    //新增详情
    handleAddDetail(row){
      this.openDetail = true;
      //给预约id复制
      this.formDetail.appointId = row.appointId
      //营地id
      this.formDetail.campId = row.campId
    },
    // 取消按钮
    cancelDetail() {
      this.openDetail = false;
      this.price = 0
      this.resetDetail();
    },
    // 表单重置
    resetDetail() {
      this.showProject=false
      this.showActivity=false
      this.showCampsite=false

      this.formDetail = {
        detailId: null,
        appointId: null,
        type: null,
        campsiteId: null,
        projectId: null,
        activityId: null,
        number: null,
        unitPrice: null

      };
      this.resetForm("form");
    },
    /** 查询预约详情列表 */
    getDetailsList(appointId) {
      this.loading = true;
      listDetails({"appointId":appointId}).then(response => {
        this.detailsList = response.rows;
        this.total = response.total;
        this.loading = false;

      });
    },
    /** 提交按钮 */
    submitFormDetail() {
      this.$refs["formDetail"].validate(valid => {
        if (valid) {
          addDetails(this.formDetail).then(response => {
            this.$modal.msgSuccess("详情新增成功");
            this.openDetail = false;
            this.price = 0
            // 表单重置
            this.resetDetail()

            this.getList();
          });
        }
      });
    },

    /** 查询预约管理列表 */
    getList() {
      this.loading = true;
      listAppointment(this.queryParams).then(response => {
        this.appointmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        appointId: null,
        campId: null,
        userId: null,
        amount: null,
        appointTime: null,
        state: null,
        qrcode: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appointId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const appointId = row.appointId || this.ids
      getAppointment(appointId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.appointId != null) {
            updateAppointment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAppointment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const appointIds = row.appointId || this.ids;
      this.$modal.confirm('是否确认删除预约管理编号为"' + appointIds + '"的数据项？').then(function() {
        return delAppointment(appointIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('camp/appointment/export', {
        ...this.queryParams
      }, `appointment_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
